<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统公告管理</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
        }

        .notice-form {
            background: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        .form-group textarea {
            height: 150px;
            resize: vertical;
        }

        .btn {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }

        .btn:hover {
            background-color: #0056b3;
        }

        .btn-danger {
            background-color: #dc3545;
        }

        .btn-danger:hover {
            background-color: #c82333;
        }

        .btn-warning {
            background-color: #ffc107;
            color: #212529;
        }

        .btn-warning:hover {
            background-color: #e0a800;
        }

        .notices-list {
            background: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .notice-item {
            border-bottom: 1px solid #eee;
            padding: 15px 0;
        }

        .notice-item:last-child {
            border-bottom: none;
        }

        .notice-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }

        .notice-meta {
            font-size: 14px;
            color: #666;
            margin-bottom: 10px;
        }

        .notice-content {
            color: #444;
            line-height: 1.6;
            margin-bottom: 10px;
        }

        .top-notice {
            border-left: 4px solid #ffc107;
            padding-left: 15px;
        }

        .actions {
            text-align: right;
        }

        .hidden {
            display: none;
        }

        .filter-section {
            margin-bottom: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 5px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>系统公告管理</h1>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
        <h3>筛选公告</h3>
        <button class="btn" onclick="loadAllNotices()">全部公告</button>
        <button class="btn" onclick="loadTopNotices()">置顶公告</button>
        <div style="margin-top: 10px;">
            <label>按发布人ID筛选:
                <input type="number" id="filterPublisherId" placeholder="输入发布人ID">
                <button class="btn" onclick="loadNoticesByPublisher()">筛选</button>
            </label>
        </div>
    </div>

    <!-- 公告发布表单 -->
    <div class="notice-form">
        <h2 id="form-title">发布公告</h2>
        <form id="noticeForm">
            <input type="hidden" id="noticeId">
            <div class="form-group">
                <label for="title">公告标题:</label>
                <input type="text" id="title" name="title" maxlength="100" required>
            </div>

            <div class="form-group">
                <label for="content">公告内容:</label>
                <textarea id="content" name="content" required></textarea>
            </div>

            <div class="form-group">
                <label for="publisherId">发布人ID:</label>
                <input type="number" id="publisherId" name="publisherId" required>
            </div>

            <div class="form-group">
                <label for="isTop">是否置顶:</label>
                <select id="isTop" name="isTop">
                    <option value="0">否</option>
                    <option value="1">是</option>
                </select>
            </div>

            <button type="submit" class="btn">发布公告</button>
            <button type="button" id="cancelBtn" class="btn btn-warning hidden">取消</button>
        </form>
    </div>

    <!-- 公告列表 -->
    <div class="notices-list">
        <h2>公告列表</h2>
        <div id="noticesContainer">
            <!-- 公告项将通过JavaScript动态加载 -->
        </div>
    </div>
</div>

<script>
    // 全局变量
    const API_BASE = 'http://localhost:8181/api/notices';
    let editingNoticeId = null;

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        loadAllNotices();
        setupEventListeners();
    });

    // 设置事件监听器
    function setupEventListeners() {
        // 表单提交事件
        document.getElementById('noticeForm').addEventListener('submit', handleFormSubmit);

        // 取消编辑按钮事件
        document.getElementById('cancelBtn').addEventListener('click', cancelEdit);
    }

    // 处理表单提交
    function handleFormSubmit(event) {
        event.preventDefault();

        const notice = {
            title: document.getElementById('title').value,
            content: document.getElementById('content').value,
            publisherId: parseInt(document.getElementById('publisherId').value),
            isTop: parseInt(document.getElementById('isTop').value)
        };

        if (editingNoticeId) {
            // 更新公告
            updateNotice(editingNoticeId, notice);
        } else {
            // 新建公告
            createNotice(notice);
        }
    }

    // 加载所有公告
    function loadAllNotices() {
        loadNoticesFromAPI(API_BASE);
    }

    // 加载置顶公告
    function loadTopNotices() {
        loadNoticesFromAPI(API_BASE + '/top');
    }

    // 根据发布人加载公告
    function loadNoticesByPublisher() {
        const publisherId = document.getElementById('filterPublisherId').value;
        if (!publisherId) {
            alert('请输入发布人ID');
            return;
        }
        loadNoticesFromAPI(API_BASE + '/publisher/' + publisherId);
    }

    // 通用加载公告函数
    function loadNoticesFromAPI(url) {
        fetch(url)
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    displayNotices(result.data);
                } else {
                    alert('加载公告失败: ' + result.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('加载公告时发生错误');
            });
    }

    // 显示公告列表
    function displayNotices(notices) {
        const container = document.getElementById('noticesContainer');

        if (!notices || notices.length === 0) {
            container.innerHTML = '<p>暂无公告</p>';
            return;
        }

        let html = '';
        notices.forEach(notice => {
            html += `
          <div class="notice-item ${notice.isTop === 1 ? 'top-notice' : ''}">
            <div class="notice-title">${escapeHtml(notice.title)} ${notice.isTop === 1 ? '<span style="color: #ffc107;">[置顶]</span>' : ''}</div>
            <div class="notice-meta">
              发布人ID: ${notice.publisherId} |
              发布时间: ${formatDate(notice.publishTime)}
            </div>
            <div class="notice-content">${escapeHtml(notice.content)}</div>
            <div class="actions">
              <button class="btn" onclick="editNotice(${notice.noticeId})">编辑</button>
              <button class="btn btn-danger" onclick="deleteNotice(${notice.noticeId})">删除</button>
            </div>
          </div>
        `;
        });

        container.innerHTML = html;
    }

    // 创建新公告
    function createNotice(notice) {
        fetch(API_BASE, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(notice)
        })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    alert('公告发布成功');
                    resetForm();
                    loadAllNotices();
                } else {
                    alert('公告发布失败: ' + result.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('发布公告时发生错误');
            });
    }

    // 编辑公告
    function editNotice(noticeId) {
        fetch(`${API_BASE}/${noticeId}`)
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    const notice = result.data;
                    // 填充表单
                    document.getElementById('noticeId').value = notice.noticeId;
                    document.getElementById('title').value = notice.title;
                    document.getElementById('content').value = notice.content;
                    document.getElementById('publisherId').value = notice.publisherId;
                    document.getElementById('isTop').value = notice.isTop;

                    // 更新界面状态
                    document.getElementById('form-title').textContent = '编辑公告';
                    document.getElementById('cancelBtn').classList.remove('hidden');

                    editingNoticeId = noticeId;

                    // 滚动到表单顶部
                    document.querySelector('.notice-form').scrollIntoView({ behavior: 'smooth' });
                } else {
                    alert('获取公告详情失败: ' + result.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('获取公告详情时发生错误');
            });
    }

    // 更新公告
    function updateNotice(noticeId, notice) {
        fetch(`${API_BASE}/${noticeId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(notice)
        })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    alert('公告更新成功');
                    resetForm();
                    loadAllNotices();
                } else {
                    alert('公告更新失败: ' + result.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('更新公告时发生错误');
            });
    }

    // 删除公告
    function deleteNotice(noticeId) {
        if (!confirm('确定要删除这条公告吗？')) {
            return;
        }

        fetch(`${API_BASE}/${noticeId}`, {
            method: 'DELETE'
        })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    alert('公告删除成功');
                    loadAllNotices();
                } else {
                    alert('公告删除失败: ' + result.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('删除公告时发生错误');
            });
    }

    // 取消编辑
    function cancelEdit() {
        resetForm();
    }

    // 重置表单
    function resetForm() {
        document.getElementById('noticeForm').reset();
        document.getElementById('noticeId').value = '';
        document.getElementById('form-title').textContent = '发布公告';
        document.getElementById('cancelBtn').classList.add('hidden');
        editingNoticeId = null;
    }

    // 工具函数：转义HTML特殊字符
    function escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };

        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }

    // 工具函数：格式化日期
    function formatDate(dateString) {
        try {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        } catch (e) {
            return dateString;
        }
    }

    // 暴露全局函数供HTML调用
    window.editNotice = editNotice;
    window.deleteNotice = deleteNotice;
    window.loadAllNotices = loadAllNotices;
    window.loadTopNotices = loadTopNotices;
    window.loadNoticesByPublisher = loadNoticesByPublisher;
</script>
</body>
</html>
